/**
 * @file 74HC4051.c
 * @brief 八选一模拟IO复用
 * @author wangh (wanghuan3037@fiberhome.com)
 * @version 1.0
 * @date 2021-03-10
 * @copyright Copyright (c) 2021  烽火通信
 */ 
#include "74HC4051.h"

#undef LOG_LEVEL_
#define LOG_LEVEL_ 	LOG_LVL_ASSERT
#include "bsp_log.h"


int8_t HC4051_Init( Hc4051_t *obj, PinNames pin_a0, PinNames pin_a1, PinNames pin_a2, PinNames pin_en )
{
    if (obj == NULL)
        return -1;

    if (obj->IsInitialized)
    {
        log_e( "HC4051_Init error: has already Initialized\r\n" );
        return -1;
    }

    obj->IsInitialized = true;
    GpioInit( &obj->A0, pin_a0, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    GpioInit( &obj->A1, pin_a1, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    GpioInit( &obj->A2, pin_a2, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    GpioInit( &obj->EN, pin_en, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );

    return 0;
}

void HC4051_DeInit( Hc4051_t *obj )
{
    if ((obj) && (obj->IsInitialized))
    {
        obj->IsInitialized = false;
        GpioInit( &obj->A0, obj->A0.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &obj->A1, obj->A1.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &obj->A2, obj->A2.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &obj->EN, obj->EN.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    }
}

int8_t HC4051_Select( Hc4051_t *obj, uint8_t Yn )
{
    if (obj == NULL)
        return -1;
    
    if ( obj->IsInitialized == false )
    {
        log_e( "HC4051_Select error: no Initialized\r\n" );
        return -1;
    }

    if ( Yn > 7 )
        return -1;

    GpioWrite( &obj->A0, ((Yn & 0x01) ? 1 : 0) );
    GpioWrite( &obj->A1, ((Yn & 0x02) ? 1 : 0) );
    GpioWrite( &obj->A2, ((Yn & 0x04) ? 1 : 0) );

    return 0;
}



/*********** (C) COPYRIGHT 2021 FiberHome *****END OF FILE****/
